package devicedbgui;

import devicedbgui.data.Build;
import devicedbgui.data.Device;
import devicedbgui.data.RepairInfo;
import devicedbgui.data.RepairInfoDAO;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

/** Displays all repairs associated with the current device */
public class RepairInfoPanel extends javax.swing.JPanel {

      /** Reference to GUI class for accessing its variables */
    public GUI gui;
    Hashtable<Integer, RepairInfo> htRepairInfo = new Hashtable<Integer, RepairInfo>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
     /** Constructor creates all components belonging to panel */   
    public RepairInfoPanel() {
        initComponents();
       
    }
     /** Displays error messages */ 
  public void showError(JFrame parent, String error)
    {
        JOptionPane.showMessageDialog(parent, error);
    }
    /** Displays repairs associated with build */
    public void showRepairInfos(GUI gui, Build build)
    {
        this.gui = gui;
        
        RepairInfoDAO dd = new RepairInfoDAO(gui.connection);
        try {
            ArrayList<RepairInfo> records = dd.selectByBuildEx(build.idBuild);
            DefaultTableModel model = (DefaultTableModel)tblRepairInfo.getModel();
            model.getDataVector().clear();
            int index = 0;      
           
            for (RepairInfo item : records){ 
                 
                htRepairInfo.put(new Integer(index++), item);
                model.addRow(new Object[]{item.idRepairInfo, (item.timeEntered == null ? "" : sdf.format(item.timeEntered)), item.description, 
                item.timeSpent, item.changesMade, item.costEstimate, item.Build_idBuild,
                item.deviceName , item.deviceSerial});
            }
             
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
         
    }
    /** Displays repairs associated with device */
    public void showRepairInfos(GUI gui, Device device)
    {
        this.gui = gui;
        
        RepairInfoDAO dd = new RepairInfoDAO(gui.connection);
        try {
            ArrayList<RepairInfo> records = dd.selectByDeviceEx(device.record);
            DefaultTableModel model = (DefaultTableModel)tblRepairInfo.getModel();
            model.getDataVector().clear();
            int index = 0;                                
            for (RepairInfo item : records){ 
                htRepairInfo.put(new Integer(index++), item);
                model.addRow(new Object[]{item.idRepairInfo, (item.timeEntered == null ? "" : sdf.format(item.timeEntered)), item.description, 
                item.timeSpent, item.changesMade, item.costEstimate, item.Build_idBuild,
                item.deviceName , item.deviceSerial});
            }
             
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
    }
    /** Displays all repairs available in database  */
    public void showAll(GUI gui)
    {
        this.gui = gui;
        
        RepairInfoDAO dd = new RepairInfoDAO(gui.connection);
        try {
            ArrayList<RepairInfo> records = dd.selectAllEx();
            DefaultTableModel model = (DefaultTableModel)tblRepairInfo.getModel();
            model.getDataVector().clear();
            int index = 0;                                
            for (RepairInfo item : records){  
                htRepairInfo.put(new Integer(index++), item);
                model.addRow(new Object[]{item.idRepairInfo, (item.timeEntered == null ? "" : sdf.format(item.timeEntered)), item.description, 
                item.timeSpent, item.changesMade, item.costEstimate, item.Build_idBuild,
                item.deviceName , item.deviceSerial});
            }
             
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
    }
     /** Refreshes display of list of builds in database */
    public void update()
    {
        RepairInfoDAO dd = new RepairInfoDAO(gui.connection);
        try {
           
            
            ArrayList<RepairInfo> records = dd.selectByBuildEx(Integer.valueOf(gui.getBuildId()));
            DefaultTableModel model = (DefaultTableModel)tblRepairInfo.getModel();
            model.getDataVector().clear();
            int index = 0;  
           
           htRepairInfo.clear();
            for (RepairInfo item : records){ 
                
                htRepairInfo.put(new Integer(index++), item);
                model.addRow(new Object[]{item.idRepairInfo, (item.timeEntered == null ? "" : sdf.format(item.timeEntered)), item.description, 
                item.timeSpent, item.changesMade, item.costEstimate, item.Build_idBuild,
                item.deviceName , item.deviceSerial});
            }
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        //tblRepairInfo.validate();
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblRepairInfo = new javax.swing.JTable() {public Component prepareRenderer(TableCellRenderer renderer,
            int rowIndex, int vColIndex) {
            Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
            if ((c instanceof JComponent)&& ((vColIndex==2)||(vColIndex==4))) {
                JComponent jc = (JComponent)c;
                jc.setToolTipText(String.valueOf(getValueAt(rowIndex, vColIndex)));
            }
            if (rowIndex % 2 == 0 && !tblRepairInfo.isRowSelected(rowIndex)) {
                c.setBackground(new Color(237, 242, 251));
            }
            else if (tblRepairInfo.isRowSelected(rowIndex)){c.setBackground(new Color(184, 207, 229));}
            else { c.setBackground(getBackground());}
            return c;
        }
    }
    ;
    btnAdd = new javax.swing.JButton();
    btnEdit = new javax.swing.JButton();
    btnDelete = new javax.swing.JButton();
    btnSave = new javax.swing.JButton();

    tblRepairInfo.setAutoCreateRowSorter(true);
    tblRepairInfo.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null}
        },
        new String [] {
            "RepairInfo ID", "Time Entered", "Description", "Time Spent", "Changes Made", "Cost Estimate", "Build ID", "Device name", "Device serial"
        }
    ) {
        boolean[] canEdit = new boolean [] {
            false, false, false, false, false, false, false, false, false
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    tblRepairInfo.setGridColor(new java.awt.Color(204, 204, 255));
    tblRepairInfo.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    TableColumn column=tblRepairInfo.getColumnModel().getColumn(2);
    column.setPreferredWidth(200);
    column=tblRepairInfo.getColumnModel().getColumn(4);
    column.setPreferredWidth(200);
    column=tblRepairInfo.getColumnModel().getColumn(0);
    column.setMaxWidth(140);
    column=tblRepairInfo.getColumnModel().getColumn(6);
    column.setMaxWidth(130);

    jScrollPane1.setViewportView(tblRepairInfo);

    btnAdd.setText("Add");
    btnAdd.setMnemonic(KeyEvent.VK_D);
    btnAdd.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnAddActionPerformed(evt);
        }
    });

    btnEdit.setText("Edit");
    btnEdit.setMnemonic(KeyEvent.VK_I);
    btnEdit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnEditActionPerformed(evt);
        }
    });

    btnDelete.setText("Delete");
    btnDelete.setMnemonic(KeyEvent.VK_DELETE);
    btnDelete.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnDeleteActionPerformed(evt);
        }
    });

    btnSave.setText("Save");
    btnSave.setMnemonic(KeyEvent.VK_S);
    btnSave.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnSaveActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(btnSave)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(btnAdd)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(btnEdit)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(btnDelete)
            .addContainerGap(260, Short.MAX_VALUE))
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAdd, btnDelete, btnEdit, btnSave});

    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(11, 11, 11)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btnAdd)
                .addComponent(btnEdit)
                .addComponent(btnDelete)
                .addComponent(btnSave))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
            .addContainerGap())
    );
    }// </editor-fold>//GEN-END:initComponents
/** Add new repair to database */
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
//if (gui.connection == null)
        //return;
    EditRepairInfoDlg dlg = new EditRepairInfoDlg(gui, null, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB){
        update();
    }
}//GEN-LAST:event_btnAddActionPerformed
/** Edit repair information */
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
int[] selected = tblRepairInfo.getSelectedRows();  
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    RepairInfo item = htRepairInfo.get(new Integer(selected[0]));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    gui.setBuildId(String.valueOf(item.Build_idBuild));
    EditRepairInfoDlg dlg = new EditRepairInfoDlg(gui, item, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB){
        htRepairInfo.remove(new Integer(selected[0]));        
        htRepairInfo.put(new Integer(selected[0]), dlg.repairInfo);
        
        update();
    }
}//GEN-LAST:event_btnEditActionPerformed
/* Delete selected repair information from database */
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
int[] selected = tblRepairInfo.getSelectedRows();  
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    // ask user if he surely wants to delete this record
    int option = JOptionPane.showConfirmDialog(gui.frame, "Are you sure to delete selected record(s)?", "Confirmation", JOptionPane.YES_NO_OPTION);
    if (option == JOptionPane.YES_OPTION)
    {        
        RepairInfoDAO dd = new RepairInfoDAO(gui.connection);
        try {
            for (int i = 0; i < selected.length; i++){
                RepairInfo item = htRepairInfo.get(new Integer(selected[i]));   
                dd.delete(item.idRepairInfo);
                htRepairInfo.remove(new Integer(selected[i]));

            }           
            
        } catch (Exception e)
        {
            JOptionPane.showMessageDialog(gui.frame, e.toString());
        }
        update();
    }
}//GEN-LAST:event_btnDeleteActionPerformed
/* Save repair data to local computer */
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed


    JFileChooser fileChooser = new JFileChooser(".");
        fileChooser.setDialogTitle("Save Repair Information");
        fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setFileFilter(new FileFilter() {

            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".csv") || f.isDirectory();
            }
            public String getDescription() {
                return "*.csv";
            }
        });
    if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION){
       File file = fileChooser.getSelectedFile();
if (file.getName().indexOf('.')==-1){
    file = new File(file.getAbsolutePath()+".csv");
}  
   try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            bw.write("RepairInfoID,TimeEntered,Description,TimeSpent,ChangesMade,CostEstimate,BuildID,DeviceName,DeviceSerial\r\n");
            for (RepairInfo item : htRepairInfo.values()){
                bw.write(String.format("%d,%s,%s,%s,%s,%s,%d,%s,%s\r\n", 
                        new Object[]{item.idRepairInfo, item.timeEntered, item.description, 
                        item.timeSpent, item.changesMade, item.costEstimate, item.Build_idBuild,
                        item.deviceName , item.deviceSerial}));
            }
            bw.flush();
            bw.close();
            JOptionPane.showMessageDialog(gui.frame, "File has been saved successfully");
        }
    catch (Exception e){
            JOptionPane.showMessageDialog(gui.frame, e.toString());
        }
    }
}//GEN-LAST:event_btnSaveActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnSave;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblRepairInfo;
    // End of variables declaration//GEN-END:variables

}
